<template>
  <el-menu ref="topNavMenu" :default-active="activeMenu" mode="horizontal" @select="(P_Unid) => handleSelect(P_Unid,true)">
    <template v-for="(item, index) in topMenus">
      <el-menu-item :style="{ '--theme': theme }" :class="[Heze ? 'hz-menu-item' : '', Qianj ? 'qj-menu-item' : '', KeYan ? 'ky-menu-item' : '']" :index="item.value" :key="index" v-if="index < visibleNumber">
        <svg-icon :icon-class="item.icon" />
        {{ item.label }}
      </el-menu-item>
    </template>

    <!-- 顶部菜单超出数量折叠 -->
    <el-submenu :class="[Heze ? 'hz-submenu-item' : '']" :style="{ '--theme': theme }" index="more" v-if="topMenus.length > visibleNumber">
      <template slot="title"><span style="padding:0 10px" class="hc-min-title">更多菜单</span></template>

      <template v-for="(item, index) in topMenus">
        <el-menu-item :index="item.value" :key="index" v-if="index >= visibleNumber">
          <svg-icon :icon-class="item.icon" />
          {{ item.label }}
        </el-menu-item>
      </template>
    </el-submenu>
  </el-menu>
</template>

<script>
import { constantRoutes } from "@/router";
import { queryModuleType } from "../../api/system/moduleInfo/api.js";
import { getRouters } from '../../api/router'
import { getFirstShowRouter } from 'hc-core/utils/index';
import { getToken, setToken, removeToken } from '../../utils/auth'
import { getRouterTree, getQueryString } from '../../utils/ruoyi';
import { mapGetters } from 'vuex';
// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile'];

export default {
  data()
  {
    return {
      topMenus: [],
      // 顶部栏初始数
      visibleNumber: window.HC_config.VUE_APP_TOP_NUM || 5,
      // 当前激活菜单的 index
      currentIndex: undefined,
      activeMenu: null,
      // 菏泽主题
      Heze: window.HC_config.VUE_APP_HEZE,
      // 潜江高新投样式
      Qianj: window.HC_config.VUE_APP_QJGXT,
      // 文字是否间隔显示
      KeYan: window.HC_config.VUE_APP_TEXT_JUSTIFY || false
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    theme()
    {
      return this.$store.state.settings.theme;
    },
    // 顶部显示菜单
    // topMenus() {
    //   let topMenus = [];
    //   this.routers.map((menu) => {
    //     if (menu.hidden !== true) {
    //       // 兼容顶部栏一级菜单内部跳转
    //       if (menu.path === "/") {
    //         topMenus.push(menu.children[0]);
    //       } else {
    //         topMenus.push(menu);
    //       }
    //     }
    //   });
    //   return topMenus;
    // },
    // 所有的路由信息
    routers()
    {
      return this.$store.state.permission.topbarRouters;
    },
    // 设置子路由
    childrenMenus()
    {
      var childrenMenus = [];
      this.routers.map((router) =>
      {
        for (var item in router.children)
        {
          if (router.children[item].parentPath === undefined)
          {
            if (router.path === "/")
            {
              router.children[item].path = "/" + router.children[item].path;
            } else
            {
              if (!this.ishttp(router.children[item].path))
              {
                //cs 2022-8-16 移除路径叠加逻辑
                // router.children[item].path = router.path + "/" + router.children[item].path;
              }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });
      return constantRoutes.concat(childrenMenus);
    },
    // 默认激活的菜单
    // activeMenu() {
    //   const path = this.$route.path;
    //   let activePath = path;
    //   if (path !== undefined && path.lastIndexOf("/") > 0 && hideList.indexOf(path) === -1) {
    //     const tmpPath = path.substring(1, path.length);
    //     activePath = "/" + tmpPath.substring(0, tmpPath.indexOf("/"));
    //     this.$store.dispatch('app/toggleSideBarHide', false);
    //   } else if (!this.$route.children) {
    //     activePath = path;
    //     //没有子级也不隐藏 菜单栏 cs 2022-9-15
    //     this.$store.dispatch('app/toggleSideBarHide', false);
    //   }
    //   this.activeRoutes(activePath);
    //   return activePath;
    // },
  },
  beforeMount()
  {
    window.addEventListener('resize', this.setVisibleNumber)
  },
  beforeDestroy()
  {
    window.removeEventListener('resize', this.setVisibleNumber)
  },
  mounted()
  {
    // this.setVisibleNumber();
    this.getModuleClass();
  },
  methods: {
    //获取模块分类作为顶部分类菜单
    getModuleClass()
    {

      queryModuleType().then((res) =>
      {
        this.topMenus = res.result.data.map((e) =>
        {
          return {
            label: e.typeCommonname,
            value: e.unid,
            icon: e.icon || "menu",
            mrdklj: e.mrdklj
          };
        });
        if (this.topMenus.length > 0)
        {
          let moduleTypeUnid = localStorage.getItem("activeModuleType_" + this.userInfo.unid);
          if (moduleTypeUnid)
          {
            let findIndex = this.topMenus.findIndex(pre_item =>
            {
              return pre_item.value == moduleTypeUnid;
            })
            if (findIndex > -1)
            {
              this.activeMenu = moduleTypeUnid;
            }
            else
            {
              this.activeMenu = this.topMenus[0].value;
            }
          }
          else
          {
            this.activeMenu = this.topMenus[0].value;
          }
          this.handleSelect(this.activeMenu, false);
        }
      });
    },
    // 根据宽度计算设置显示栏数
    setVisibleNumber()
    {
      const width = document.body.getBoundingClientRect().width / 3;
      this.visibleNumber = parseInt(width / 85);
    },
    //提供给外部切换顶部导航栏的
    changeTopByIndex(P_ModuleTypeUnid)
    {
      if (P_ModuleTypeUnid && this.$refs.topNavMenu.items[P_ModuleTypeUnid])
      {
        this.$refs.topNavMenu.handleItemClick(this.$refs.topNavMenu.items[P_ModuleTypeUnid]);
      }
      // this.handleSelect(topMenuId);
    },
    // 菜单选择事件
    handleSelect(P_Unid, P_Flag)
    {
      //缓存到localStorage
      let topMenuItem = this.topMenus.find(item => item.value === P_Unid);

      console.log("--------触发修改1---------")
      console.log(P_Flag);
      console.log(topMenuItem);
      console.log("--------触发修改1---------")

      if (topMenuItem)
      {
        if (topMenuItem.label == '快捷方式')
        {
          if (topMenuItem.mrdklj && P_Flag)
          {
            this.$router.push(topMenuItem.mrdklj)
          }
          if (topMenuItem.children && topMenuItem.children.length > 0 && P_Type == 'click')
          {
            this.$router.push(topMenuItem.children[0].path || topMenuItem.children[0].children[0].path)
          }
          return;
        }
        localStorage.setItem("activeModuleType_" + this.userInfo.unid, P_Unid);
        this.currentIndex = P_Unid;
        this.$store.commit("app/SET_TOPMENUITEM", topMenuItem);
        console.log(topMenuItem, "=====================cs")
        var mrdklj = topMenuItem.mrdklj;  // 默认打开路径
        //cs 2022-9-15 查询此模块分类下的路由
        if (!topMenuItem.children)
        {
          console.log(1)
          getRouters({ moduleTypeStr: P_Unid }).then(res =>
          {
            let routes = res.result || [];
            let routesTree = getRouterTree(routes, "parentId", "id");
            topMenuItem.children = routesTree || [];
            this.activeRoutes(topMenuItem);
            this.$store.dispatch('app/toggleSideBarHide', false);
            if (mrdklj && P_Flag)
            {
              this.$router.push(mrdklj)
            }
            if (window.HC_config && window.HC_config.VUE_DCDB_TYPE_UNID == P_Unid && P_Flag)
            {
              let findDbsy = routes.find(preRouter =>
              {
                return preRouter.path.indexOf("/dcdb/dbsy") != -1;
              });
              console.log(findDbsy, "================cs");
              if (findDbsy && findDbsy.children && findDbsy.children instanceof Array && findDbsy.children.length != 0)
              {
                this.$router.push({ path: findDbsy.children[0].path });
              }
              else
              {
                this.$router.push({ path: findDbsy.path });
              }
            }
            else if(P_Flag)
            {
              console.log(4)
              if (window.HC_config && window.HC_config.VUE_APP_AUTO_FIRST_MENU)
              {
                if (routes && routes instanceof Array && routes.length != 0)
                {
                  let curRouter = getFirstShowRouter(routes);
                  console.log(curRouter, 'curRouter4')
                  if (P_Flag)
                  {
                    this.$store.commit("SET_SIDEBAR_CHILD_ROUTERS", curRouter.children || []);
                  }
                  // if (curRouter && curRouter.path.indexOf("system") == -1){
                  if (curRouter.children && curRouter.children instanceof Array && curRouter.children.length != 0)
                  {
                    this.$router.push({ path: getFirstShowRouter(curRouter.children).path });
                  }
                  else
                  {
                    this.$router.push({ path: curRouter.path });
                  }
                  // }
                }
              }
            }
          })
        }
        else
        {
          console.log(2)
          this.activeRoutes(topMenuItem);
          this.$store.dispatch('app/toggleSideBarHide', false);
          if (mrdklj)
          {
            this.$router.push(mrdklj)
          }
          if (window.HC_config && window.HC_config.VUE_DCDB_TYPE_UNID == P_Unid && P_Flag)
          {
            let findDbsy = topMenuItem.children.find(preRouter =>
            {
              return preRouter.path.indexOf("/dcdb/dbsy") != -1;
            });
            console.log(findDbsy, "================cs");
            if (findDbsy && findDbsy.children && findDbsy.children instanceof Array && findDbsy.children.length != 0)
            {
              this.$router.push({ path: findDbsy.children[0].path });
            }
            else
            {
              this.$router.push({ path: findDbsy.path });
            }
          }
          else
          {
            console.log(3)
            if (window.HC_config && window.HC_config.VUE_APP_AUTO_FIRST_MENU && window.HC_config.VUE_APP_AUTO_FIRST_MENU == true)
            {
              if (topMenuItem.children && topMenuItem.children instanceof Array && topMenuItem.children.length != 0)
              {
                let curRouter = getFirstShowRouter(topMenuItem.children);
                console.log(curRouter, 'curRouter3')
                this.$store.commit("SET_SIDEBAR_CHILD_ROUTERS", curRouter.children || []);
                if (curRouter && curRouter.path.indexOf("system") == -1)
                {
                  if (curRouter.children && curRouter.children instanceof Array && curRouter.children.length != 0)
                  {
                    this.$router.push({ path: getFirstShowRouter(curRouter.children).path });
                  }
                  else
                  {
                    this.$router.push({ path: curRouter.path });
                  }
                }
              }
            }
          }
        }
      }

      // const route = this.routers.find(item => item.path === key);
      // if (this.ishttp(key)) {
      //   // http(s):// 路径新窗口打开
      //   window.open(key, "_blank");
      // } else if (!route || !route.children) {
      //   // 没有子路由路径内部打开
      //   this.$router.push({ path: key });
      //   this.$store.dispatch('app/toggleSideBarHide', true);
      // } else {
      //   // 显示左侧联动菜单
      //   this.activeRoutes(key);
      //   this.$store.dispatch('app/toggleSideBarHide', false);
      // }
    },
    // 当前激活的路由
    activeRoutes(p_TopMenuItem)
    {
      console.log(p_TopMenuItem)
      console.log(p_TopMenuItem.children)
      // var routes = [];
      // if (this.childrenMenus && this.childrenMenus.length > 0) {
      //   this.childrenMenus.map((item) => {
      //     if (key == item.parentPath || (key == "index" && "" == item.path)) {
      //       routes.push(item);
      //     }
      //   });
      // }
      // if (routes.length > 0) {
      //   this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      // }
      this.$store.commit("SET_SIDEBAR_ROUTERS", p_TopMenuItem.children || []);
    },
    ishttp(url)
    {
      return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
    }
  }
};
</script>

<style lang="scss" scoped>
.topmenu-container.el-menu--horizontal > .hz-menu-item {
  color: #fff !important;
  height: 60px !important;
  line-height: 60px !important;
}
.topmenu-container.el-menu--horizontal > .hz-menu-item:hover {
  color: #{"var(--theme)"} !important;
}
.topmenu-container.el-menu--horizontal > .hz-menu-item.is-active {
  color: #{"var(--theme)"} !important;
  background-color: #ffffff;
  &::after {
    content: "";
    height: 0 !important;
  }
}
.topmenu-container.el-menu--horizontal > .el-menu-item {
  float: left;
  height: 64px;
  line-height: 64px;
  color: #999093;
  padding: 0 10px !important;
  margin: 0px 10px !important;
  border: 0 !important;
}

.topmenu-container.el-menu--horizontal > .el-menu-item.is-active,
.el-menu--horizontal > .el-submenu.is-active .el-submenu__title {
  color: #{"var(--theme)"};

  &::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 2px;
    background-color: #{"var(--theme)"};
    bottom: 0px;
    left: 0;
  }
}

/* submenu item */
.topmenu-container.el-menu--horizontal > .el-submenu .el-submenu__title {
  float: left;
  border-radius: 5px;
  height: 50px !important;
  line-height: 50px !important;
  color: #999093;
  padding: 0 10px !important;
  margin: 0px 10px !important;
  border: 0 !important;

  &:hover {
    background-color: rgba(0, 0, 0, 0.025);
  }
}
.topmenu-container.el-menu--horizontal
  .hz-submenu-item
  ::v-deep
  .el-submenu__title {
  color: #ffffff !important;
  i {
    color: #fff;
  }
  &:hover {
    background-color: rgba(0, 0, 0, 0.025);
  }
}
</style>
